package com.alm.handle.proxy.proxy;

import com.alm.handle.proxy.decoder.MyDecoder;
import com.alm.handle.proxy.handler.ProxyServerChannelHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class ProxyServer {
    @Resource
    private ProxyServerChannelHandler proxyServerChannelHandler;

    public ProxyServer() {

    }

    public void run(int prot) throws InterruptedException, IOException {
         final EventLoopGroup boss = new NioEventLoopGroup();
         final EventLoopGroup worker = new NioEventLoopGroup();

        try {
        ServerBootstrap server = new ServerBootstrap();//启动类
        server.group(boss, worker)
                .channel(NioServerSocketChannel.class)
                //BACKLOG用于构造服务端套接字ServerSocket对象，标识当服务器请求处理线程全满时，用于临时存放已完成三次握手的请求的队列的最大长度
                .option(ChannelOption.SO_BACKLOG, 512)
                .option(ChannelOption.TCP_NODELAY, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel sc) throws Exception {
                        sc.pipeline().addFirst(new IdleStateHandler(0, 0, 60, TimeUnit.SECONDS));
                        sc.pipeline().addFirst(new MyDecoder(true));
                        sc.pipeline().addLast(proxyServerChannelHandler);
                    }
                });
        ChannelFuture f = server.bind(prot).sync();
        if(f.isSuccess()){
            System.out.println("server start on "+prot);
        }
            f.channel().closeFuture().sync();
        }
        catch(Exception e) {
        e.printStackTrace();
    }finally {
        System.out.println("server shutdown.");
        boss.shutdownGracefully();
        worker.shutdownGracefully();
    }
    }

}
